CODE 138. Linked List Cycle

版权声明:本文为博主原创文章,转载请注明出处,谢谢!

版权声明:本文为博主原创文章,转载请注明出处:http://blog.jerkybible.com/2013/11/24/2013-11-24-CODE 138 Linked List Cycle/

访问原文「CODE 138. Linked List Cycle

Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public boolean hasCycle(ListNode head) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
if(null == head){
return false;
}
ListNode first = head;
ListNode second = head;
while(first.next != null && first.next.next !=null){
if(first.next.equals(second) || first.next.next.equals(second)){
return true;
}
first = first.next.next;
second = second.next;
}
if(first.next != null && first.next.equals(second)){
return true;
}
return false;
}
Jerky Lu wechat
欢迎加入微信公众号